package com.ruiysoft.security.point;

import com.ruiysoft.pub.core.ResultCode;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by geyon on 2018/9/20.
 */
@Component("customAuthExceptionEntryPoint")
public class CustomAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Map<String, Object> map = new HashMap<>();
        Throwable cause = authException.getCause();
        if(cause instanceof InvalidTokenException) {
            map.put("success", false);
            map.put("bizCode", ResultCode.CODE_AUTH_ERROR);
            map.put("bizMessage", "无效的token");
        }else{
            map.put("success", false);
            map.put("bizCode", ResultCode.CODE_AUTH_ERROR);
            map.put("bizMessage", "访问此资源需要完全的身份验证");
        }
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}
